package com.google.code.sip.ucenter.ws.resources.benchmark;

import java.util.concurrent.CyclicBarrier;
import static org.junit.Assert.assertEquals;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;

public class WSBenchmarkThread extends Thread {
	private int repeats;
	private int countMax;
	private CyclicBarrier barrier;
	private int threadNum;
	Client client = Client.create();
	WebResource resource = client
			.resource("http://121.14.211.78:8080/uc/ws/user/login");

	public WSBenchmarkThread(int threadNum, CyclicBarrier barrier, int repeats,
			int countMax) {
		this.threadNum = threadNum;
		this.barrier = barrier;
		this.repeats = repeats;
		this.countMax = countMax;
	}

	@Override
	public void run() {
		int count = 0;
		try {
			barrier.await();
			long beginTime = System.nanoTime();
			for (int repeat = 0; repeat < repeats; repeat++) {
				for (count = 0; count < countMax; count++) {
					MultivaluedMap<String, String> params = new MultivaluedMapImpl();
					params.add("username", "ssls");
					params.add("password", "111111");
					ClientResponse response = resource.accept(
							MediaType.APPLICATION_JSON).post(
							ClientResponse.class, params);
					assertEquals(200, response.getStatus());
					// System.out.println(response.getEntity(String.class));
					client.destroy();
				}
			}
			long endTime = System.nanoTime();
			System.out.println("调用restful接口线程" + threadNum + "执行完毕，耗时："
					+ (endTime - beginTime) + "纳秒("
					+ new Float((endTime - beginTime) / 1000000) + "毫秒)");
			barrier.await();

		} catch (Exception e) {
			System.out.println("已调用" + count + "次");
			e.printStackTrace();
		}
	}
}
